#!/usr/bin/env python
# -*- coding:utf-8 -*-
########监控机，订阅者########
from main import RedisHelper
import redis
import json
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String,Float,DATETIME
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
import time

redis_server='192.168.136.8'
redis_port=6379

def set_module():
    r=redis.Redis(host=redis_server,port=redis_port)
    module=json.dumps({'cpu':'get_load_avg','process':'get_pro_num'})
    r.set("192.168.136.11",module)

def recive_msg():
    monitor_data=subscriber.parse_response()
    #收到的是一个列表['message', 'monitor', "{'process': '372', 'ip': '192.168.136.11', 'cpu': 0.0}"]
    print "recived message:%s"%monitor_data
    #处理接收到监控数据，列表-->dict-->str
    msg=json.loads(monitor_data[-1])
    return msg
    # ip=msg['ip']
    # cpu=msg['cpu']
    # process=msg['process']

def save_mysql(msg):   #存入mysql数据库
    engine=create_engine("mysql+mysqldb://root:123456@192.168.136.8:3306/monitor",max_overflow=3)
    Base=declarative_base()
    class Data(Base):   #告诉表结构，它并不创建表
        #create table data (id INT NOT NULL AUTO_INCREMENT,ip CHAR(50) NOT NULL,cpu Float,procnum INT,date CHAR(30) NOT NULL,PRIMARY KEY (id) );
        __tablename__='data'
        id = Column(Integer,autoincrement=True,primary_key=True)
        ip = Column(String(50))
        cpu = Column(Float)
        procnum = Column(Integer)
        date = Column(String(30))
    ##创建连接，插入数据,提交
    Session = sessionmaker(bind=engine)
    session = Session()
    m = Data(ip=msg['ip'],cpu=msg['cpu'],procnum=int(msg['process']),date=time.strftime("%Y-%m-%d %H:%M:%S"))
    session.add(m)
    session.commit()

if __name__ == '__main__':
    set_module()    #把监控模板存到redis
    s=RedisHelper() #实例化模型
    subscriber=s.subscribe()    #创建一个订阅者
    while True:
        #获取监控数据
        msg=recive_msg()
        #存入mysql
        save_mysql(msg)